import requests
import pandas as pd
import datetime
from datetime import timezone


def timestamp_to_utc_str(timestamp, fmt="%Y-%m-%d %H:%M:%S"):
    """
    将时间戳转换为UTC时间字符串

    参数:
        timestamp: Unix时间戳（秒级）=]
        fmt: 输出字符串的格式
    返回:
        str: UTC时间字符串
    """
    # 创建UTC时间对象
    utc_dt = datetime.datetime.fromtimestamp(timestamp, tz=timezone.utc)

    # 格式化为字符串
    return utc_dt.strftime(fmt)+"+00:00"


API_KEY = '1zWq4Li0KlvJgokm8mJoXa8OeB2'  # dixinsuanlieth1@163.com
# url = "https://api.glassnode.com/v1/metrics/market/price_usd_ohlc?a=BTC&i=10m&referrer=charts&s=1388534400"
url = "https://api.glassnode.com/v1/metrics/market/price_usd_ohlc"
asset = "BTC"
# a=BTC&i=10m&referrer=charts&s=1388534400
parameters = {'a': asset, 'api_key': API_KEY, 'i': "10m", 'referrer': 'charts'}
response = requests.get(url, params=parameters)
data = response.json()


ret_list = []
for x in data:
    tmp_dict = x['o']
    tmp_dict['t'] = x['t']
    ret_list.append(tmp_dict)
ret_df = pd.DataFrame(ret_list)
ret_df["datetime"] = ret_df["t"].apply(lambda x: timestamp_to_utc_str(x))
ret_df.to_csv("price_usd_ohlc_all.csv", index=False)